/******************************************************************************
 * @File name   :      RedemptionServiceImpl.java
 *
 * @Author      :      JIZHANGS
 *
 * @Date        :      Jul 31, 2015
 *
 * @Copyright Notice: 
 * Copyright (c) 2015 Capgemini, Inc. All  Rights Reserved.
 * This software is published under the terms of the Capgemini Software
 * License version 1.0, a copy of which has been included with this
 * distribution in the LICENSE.txt file.
 * 
 * 
 * ----------------------------------------------------------------------------
 * Date                   Who         Version        Comments
 * Jul 31, 2015 1:10:04 PM        JIZHANGS     1.0            Initial Version
 *****************************************************************************/
package com.cap.bts.crmdp.dealer.redemption.service.impl;

import java.math.BigInteger;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;

import org.apache.commons.lang3.StringUtils;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.cap.bts.commonfunc.common.constant.SmsTemplateNoConstants;
import com.cap.bts.commonfunc.common.constant.SmsTemplateVariable;
import com.cap.bts.commonfunc.common.dto.SmsContentDetailDto;
import com.cap.bts.crmdp.dealer.dealerinfosync.dao.IDealerInfoSyncDao;
import com.cap.bts.crmdp.dealer.dealerinfosync.domain.DealerInfoRelMars;
import com.cap.bts.crmdp.dealer.member.dao.IMaintainCarPlateDao;
import com.cap.bts.crmdp.dealer.member.dao.IMaintainMemberDao;
import com.cap.bts.crmdp.dealer.member.domain.CarPlateInfo;
import com.cap.bts.crmdp.dealer.member.domain.MemberInfo;
import com.cap.bts.crmdp.dealer.purchase.dao.IMemberPackageDao;
import com.cap.bts.crmdp.dealer.purchase.domain.MemberPackageInfo;
import com.cap.bts.crmdp.dealer.redemption.dao.IPackageRedemptionDao;
import com.cap.bts.crmdp.dealer.redemption.domain.MemberPackageRedemption;
import com.cap.bts.crmdp.dealer.redemption.dto.MemberAndDealerInfoDto;
import com.cap.bts.crmdp.dealer.redemption.dto.MemberPackageInfoResultsDto;
import com.cap.bts.crmdp.dealer.redemption.dto.MemberPackagesReportDto;
import com.cap.bts.crmdp.dealer.redemption.dto.MemberQueryDto;
import com.cap.bts.crmdp.dealer.redemption.dto.RedemptionSubmitDto;
import com.cap.bts.crmdp.dealer.redemption.dto.ShowMemberPackageInfoReportDto;
import com.cap.bts.crmdp.dealer.redemption.service.IRedemptionService;
import com.cap.bts.framework.common.constant.CommonConstants;
import com.cap.bts.framework.common.exception.AppException;
import com.cap.bts.framework.common.util.Utils;
import com.cap.bts.framework.sms.service.ISmContentService;

/**
 *
 */
@Transactional(rollbackFor = AppException.class)
@Service
public class RedemptionServiceImpl implements IRedemptionService {
    private static final Logger LOGGER = Logger.getLogger(RedemptionServiceImpl.class);
    @Resource(name = "memberPackageDao")
    private IMemberPackageDao memberPackageDao;
 
    @Resource(name = "packageRedemptionDao")
    private IPackageRedemptionDao packageRedemptionDao;
    
    @Resource(name = "maintainCarPlateDao")
    IMaintainCarPlateDao maintainCarPlateDao;
    
    @Autowired
    private ISmContentService smContentService;
    @Autowired
    private IDealerInfoSyncDao dealerInfoSyncDao;
    
    @Autowired
    private IMaintainMemberDao memberDao;
    
    /**
     * {@inheritDoc} 
     * overridden:
     * @Date        :      Jul 31, 2015
     * @see com.cap.bts.crmdp.dealer.redemption.service.IRedemptionService#getPackageListByMember(com.cap.bts.crmdp.dealer.redemption.dto.MemberQueryDto)
    **/
    @Override
    public List<MemberPackageInfoResultsDto> getPackageListByMember(MemberQueryDto dto) throws AppException {
        List<MemberPackageInfoResultsDto> results=new ArrayList<MemberPackageInfoResultsDto>();
        List<CarPlateInfo> carlist =maintainCarPlateDao.getCarPlateInfoListByCarPlateOrMemberId(dto.getCarPlate(), dto.getId());
        if(carlist!=null && !carlist.isEmpty()){
            dto.setCarId(carlist.get(0).getId());
        }
        List<Object[]> list=memberPackageDao.getPackageListByMember(dto);
        if(list != null && !list.isEmpty()){
            for (int i = 0; i < list.size(); i++) {
                MemberPackageInfoResultsDto resultsDto = new MemberPackageInfoResultsDto();
                Object[] obj = (Object[]) list.get(i);
                resultsDto.setId(Long.valueOf(obj[0].toString()));
                resultsDto.setName(obj[1].toString());
                resultsDto.setPackageNumber(obj[2].toString());
                resultsDto.setStatus(Byte.valueOf(obj[3].toString()));
                resultsDto.setPurchaseDate(Utils.formatDate(CommonConstants.DATE_FORMAT_YYMMDD,(Date)obj[4]));
                resultsDto.setActiveDate(Utils.formatDate(CommonConstants.DATE_FORMAT_YYMMDD,(Date)obj[5]));
                resultsDto.setExpireDate(Utils.formatDate(CommonConstants.DATE_FORMAT_YYMMDD,(Date)obj[6]));
                List<Object[]> unUselist=packageRedemptionDao.getPackageListDetailByPackageId(resultsDto.getId(),0);
                if(unUselist!=null && !unUselist.isEmpty()){
                    BigInteger count = new BigInteger("0");
                    for(int j=0;j<unUselist.size();j++){
                        count=count.add((BigInteger)(unUselist.get(j))[4]);
                    }
                    resultsDto.setCountOfPackageLines(count);
                    resultsDto.setMemberPackageRedemptionList(unUselist);
                    resultsDto.setHasUnused(true);
                }else{
                    resultsDto.setHasUnused(false);
                }
                List<Object[]> usedlist=packageRedemptionDao.getPackageListDetailByPackageId(resultsDto.getId(),1);
                if(usedlist!=null && !usedlist.isEmpty()){
                    resultsDto.setMemberUsedPackageRedemptionList(usedlist);
                    resultsDto.setHasUsed(true);
                }else{
                    resultsDto.setHasUsed(false);
                }
                results.add(resultsDto); 
            }
        }
        return results;
    }
    
    /**
     * {@inheritDoc} 
     * overridden:
     * @Date        :      Aug 1, 2015
     * @see com.cap.bts.crmdp.dealer.redemption.service.IRedemptionService#checkActivePackage(com.cap.bts.crmdp.dealer.redemption.dto.MemberQueryDto)
    **/
    @Override
    public Boolean checkActivePackage(MemberQueryDto dto) throws AppException {
        List<CarPlateInfo> carlist =maintainCarPlateDao.getCarPlateInfoListByCarPlateOrMemberId(dto.getCarPlate(), dto.getId());
        if(carlist != null && !carlist.isEmpty()){
            CarPlateInfo carPlateInfo = carlist.get(0);
            if(carPlateInfo != null){
                dto.setCarId(carPlateInfo.getId());
                return memberPackageDao.checkActivePackage(dto);
            }
        }
        return false;
        
    }

    /**
     * {@inheritDoc} 
     * overridden:
     * @Date        :      Aug 3, 2015
     * @see com.cap.bts.crmdp.dealer.redemption.service.IRedemptionService#checkActivicationCode(com.cap.bts.crmdp.dealer.redemption.dto.RedemptionSubmitDto)
    **/
    @Override
    public MemberPackageRedemption checkActivicationCode(RedemptionSubmitDto dto) throws AppException {
        MemberPackageRedemption mpr=packageRedemptionDao.checkActivicationCode(dto);
        if(mpr!=null){
            mpr.setStatus(1);
            mpr.setRedeemDate(new Date());
            packageRedemptionDao.updateMemberPackageRedemption(mpr);
            sendSMSForRedeem(mpr);
            
        }
        return mpr;
        
    }

    @Override
    public boolean sendRedemptionCode(Long redemptionId, Long memberPackageId) throws AppException {
        //send SMS Message
        MemberPackageInfo memberPackageInfo = memberPackageDao.findById(memberPackageId);
        MemberPackageRedemption memberPackageRedemption = packageRedemptionDao.findById(redemptionId);
        if(memberPackageInfo != null && memberPackageRedemption != null){
            //Send SMS
            Map<String, String> paraMap = new HashMap<String, String>();
            paraMap.put(SmsTemplateVariable.VARIABLE_PACKAGE_NAME, memberPackageRedemption.getShortName());
            paraMap.put(SmsTemplateVariable.VARIABLE_PACKAGE_NUM, memberPackageInfo.getPackageNumber());
            paraMap.put(SmsTemplateVariable.VARIABLE_REDEEM_CODE, memberPackageRedemption.getActivicationCode());
            SmsContentDetailDto smsDto = new SmsContentDetailDto();
            smsDto.setParaMap(paraMap);
            MemberInfo memberInfo = memberDao.findById(memberPackageInfo.getActiveMemberId());
            if (memberInfo != null && Utils.notEmpty(memberInfo.getMobilePhone())) {
                 smsDto.setDestMobile(Long.valueOf(memberInfo.getMobilePhone()));
                 smsDto.setTemplateNo(SmsTemplateNoConstants.PACKAGE_REDEEM_TEMPLATE_NO);
                 smContentService.createSmsContent(smsDto);
            }
            return true;
        }
                    
        return false;
    }

    /**
     * {@inheritDoc} 
     * overridden:
     * @Date        :      2015年9月9日
     * @see com.cap.bts.crmdp.dealer.redemption.service.IRedemptionService#useActivicationCode(com.cap.bts.crmdp.dealer.redemption.dto.RedemptionSubmitDto)
    **/
    @Override
    public MemberPackageRedemption useActivicationCode(RedemptionSubmitDto dto) throws AppException {
        MemberPackageRedemption mpr=packageRedemptionDao.useActivicationCode(dto);
        if(mpr!=null){
            mpr.setStatus(1);
            mpr.setRedeemDate(new Date());
            packageRedemptionDao.updateMemberPackageRedemption(mpr);
            sendSMSForRedeem(mpr);
        }
        return mpr;
        
    }
    
    private void sendSMSForRedeem(MemberPackageRedemption mpr){
      //send SMS Message
        MemberPackageInfo memberPackageInfo = memberPackageDao.findById(mpr.getPackageId());
        if(memberPackageInfo != null && mpr.getPackageRedemptionLine() != null){
            //Send SMS
            Map<String, String> paraMap = new HashMap<String, String>();
            paraMap.put(SmsTemplateVariable.VARIABLE_REDEEM_LINE_NAME, mpr.getPackageRedemptionLine().getShortName());
            SmsContentDetailDto smsDto = new SmsContentDetailDto();
            smsDto.setParaMap(paraMap);
            MemberInfo memberInfo = memberDao.findById(memberPackageInfo.getActiveMemberId());
            if (memberInfo != null && Utils.notEmpty(memberInfo.getMobilePhone())) {
                 smsDto.setDestMobile(Long.valueOf(memberInfo.getMobilePhone()));
                 smsDto.setTemplateNo(SmsTemplateNoConstants.PACKAGE_LINE_REDEEM_TEMPLATE_NO);
                 try {
                    smContentService.createSmsContent(smsDto);
                } catch (AppException e) {
                    LOGGER.error("sendSMSForRedeem", e);
                }
            }
        }
    }

    /**
     * {@inheritDoc} 
     * overridden:
     * @Date        :      2015年9月17日
     * @see com.cap.bts.crmdp.dealer.redemption.service.IRedemptionService#checkPackage(com.cap.bts.crmdp.dealer.redemption.dto.MemberQueryDto)
    **/
    @Override
    public Boolean checkPackage(MemberQueryDto dto) throws AppException {
        List<CarPlateInfo> carlist =maintainCarPlateDao.getCarPlateInfoListByCarPlateOrMemberId(null, dto.getId());
        if(carlist != null && !carlist.isEmpty()){
            for(int i=0;i<carlist.size();i++){
                if(carlist.get(i) != null){
                    dto.setCarId(carlist.get(i).getId());
                    if(memberPackageDao.checkPackage(dto)){
                        return true;
                    }
                }
            }
        }
        return false;
    }

    /**
     * {@inheritDoc} 
     * overridden:
     * @Date        :      2015年9月17日
     * @see com.cap.bts.crmdp.dealer.redemption.service.IRedemptionService#getAllPackageListByMember(com.cap.bts.crmdp.dealer.redemption.dto.MemberQueryDto)
    **/
    @Override
    public List<MemberPackageInfoResultsDto> getAllPackageListByMember(MemberQueryDto dto)
        throws AppException {
        List<MemberPackageInfoResultsDto> results=new ArrayList<MemberPackageInfoResultsDto>();
        List<CarPlateInfo> carlist =maintainCarPlateDao.getCarPlateInfoListByCarPlateOrMemberId(null, dto.getId());
        if(carlist!=null && !carlist.isEmpty()){
            dto.setCarId(carlist.get(0).getId());
        }
        List<Object[]> list=memberPackageDao.getPackageListByMember(dto);
        if(list != null && !list.isEmpty()){
            for (int i = 0; i < list.size(); i++) {
                MemberPackageInfoResultsDto resultsDto = new MemberPackageInfoResultsDto();
                Object[] obj = (Object[]) list.get(i);
                resultsDto.setId((Long) obj[0]);
                resultsDto.setName((String)obj[1]);
                resultsDto.setPackageNumber((String)obj[2]);
                resultsDto.setStatus((Byte)obj[3]);
                resultsDto.setPurchaseDate(Utils.formatDate(CommonConstants.DATE_FORMAT_YYMMDD,(Date)obj[4]));
                resultsDto.setActiveDate(Utils.formatDate(CommonConstants.DATE_FORMAT_YYMMDD,(Date)obj[5]));
                resultsDto.setExpireDate(Utils.formatDate(CommonConstants.DATE_FORMAT_YYMMDD,(Date)obj[6]));
                List<Object[]> unUselist=packageRedemptionDao.getPackageListDetailByPackageId(resultsDto.getId(),0);
                if(unUselist!=null && !unUselist.isEmpty()){
                    BigInteger count = new BigInteger("0");
                    for(int j=0;j<unUselist.size();j++){
                        count=count.add((BigInteger)(unUselist.get(j))[4]);
                    }
                    resultsDto.setCountOfPackageLines(count);
                    resultsDto.setMemberPackageRedemptionList(unUselist);
                    resultsDto.setHasUnused(true);
                }else{
                    resultsDto.setHasUnused(false);
                }
                List<Object[]> usedlist=packageRedemptionDao.getPackageListDetailByPackageId(resultsDto.getId(),1);
                if(usedlist!=null && !usedlist.isEmpty()){
                    resultsDto.setMemberUsedPackageRedemptionList(usedlist);
                    resultsDto.setHasUsed(true);
                }else{
                    resultsDto.setHasUsed(false);
                }
                results.add(resultsDto); 
            }
        }
        return results;
    }
    

    /**
     * {@inheritDoc} 
     * overridden:
     * @Date        :      2015年9月17日
     * @see com.cap.bts.crmdp.dealer.redemption.service.IRedemptionService#getMemberAndDealerInfoDto(com.cap.bts.crmdp.dealer.redemption.dto.MemberQueryDto)
    **/
    @Override
    public List<MemberAndDealerInfoDto> getDealerInfoDto()
        throws AppException {
        return memberPackageDao.getDealerInfoDto();
    }

    /**
     * {@inheritDoc} 
     * overridden:
     * @Date        :      2015年9月18日
     * @see com.cap.bts.crmdp.dealer.redemption.service.IRedemptionService#getPackageListForReportByMember(com.cap.bts.crmdp.dealer.redemption.dto.MemberQueryDto)
    **/
    @Override
    public List<MemberPackagesReportDto> getPackageListForReportByMember(MemberQueryDto dto)
        throws AppException {
        List<MemberPackagesReportDto> resultsToShow=new ArrayList<MemberPackagesReportDto>();
        List<CarPlateInfo> carlist =maintainCarPlateDao.getCarPlateInfoListByCarPlateOrMemberId(null, dto.getId());
        if(carlist!=null && !carlist.isEmpty()){
            for(int i=0;i<carlist.size();i++){
                MemberPackagesReportDto memberPackagesReportDto = new MemberPackagesReportDto();
                memberPackagesReportDto.setCarPlate(carlist.get(i).getCarPlate());
                List<ShowMemberPackageInfoReportDto> results=new ArrayList<ShowMemberPackageInfoReportDto>();
                dto.setCarId(carlist.get(i).getId());
                List<Object[]> list = memberPackageDao.getPackageListForReportByMember(dto);
                if(list != null && !list.isEmpty()){
                    for (int j = 0; j < list.size(); j++) {
                        ShowMemberPackageInfoReportDto resultsDto = new ShowMemberPackageInfoReportDto();
                        Object[] obj = (Object[]) list.get(j);
                        resultsDto.setPrice((Double) obj[0]);
                        resultsDto.setName((String)obj[1]);
                        resultsDto.setPackageNumber((String)obj[2]);
                        resultsDto.setStatus((Byte)obj[3]);
                        resultsDto.setPurchaseDate(Utils.formatDate(CommonConstants.DATE_FORMAT_YYMMDD,(Date)obj[4]));
                        resultsDto.setActiveDate(Utils.formatDate(CommonConstants.DATE_FORMAT_YYMMDD,(Date)obj[5]));
                        resultsDto.setExpireDate(Utils.formatDate(CommonConstants.DATE_FORMAT_YYMMDD,(Date)obj[6]));
                        BigInteger id = (BigInteger) obj[7];
                        resultsDto.setId(id.longValue());
                        resultsDto.setCarPlate(carlist.get(i).getCarPlate());
                        if(resultsDto.getStatus() == 3){
                            resultsDto.setHasUnActived(true);
                        }else{
                            resultsDto.setHasUnActived(false);
                        }
                        List<Object[]> memberPackageList=packageRedemptionDao.getPackageListReportDetailByPackageId(resultsDto.getId());
                        if(memberPackageList!=null && !memberPackageList.isEmpty()){
                            resultsDto.setMemberPackageList(memberPackageList);
                            resultsDto.setHasPackage(true);
                        }else{
                            resultsDto.setHasPackage(false);
                        }
                        List<String> benfitList = packageRedemptionDao.getPackageMemberBenfitByPackageId(resultsDto.getId());
                        if(benfitList != null && !benfitList.isEmpty()){
                            String benfit = benfitList.get(0);
                            resultsDto.setBenfit(benfit);
                        }
                      //套餐使用明细
                        List<Object[]> packageRedemList = packageRedemptionDao.getPackageRedemListByPackageId(resultsDto.getId());
                        if(packageRedemList != null && !packageRedemList.isEmpty()){
                            resultsDto.setPackageRedemList(packageRedemList);
                        }
                        results.add(resultsDto); 
                    }
                    memberPackagesReportDto.setShowMemberPackageInfoReportList(results);
                }
                resultsToShow.add(memberPackagesReportDto);
            }
        }
        return resultsToShow;
    }

    /**
     * {@inheritDoc} 
     * overridden:
     * @Date        :      2015年10月22日
     * @see com.cap.bts.crmdp.dealer.redemption.service.IRedemptionService#getDealerInfoDtoByDealerId(java.lang.Long)
    **/
    @Override
    public List<MemberAndDealerInfoDto> getMemberAndDealerInfoDtoByMemberId(Long id) throws AppException {
        return memberPackageDao.getMemberAndDealerInfoDtoByMemberId(id);
    }

    /**
     * {@inheritDoc} 
     * overridden:
     * @Date        :      2015年10月23日
     * @see com.cap.bts.crmdp.dealer.redemption.service.IRedemptionService#getPackageListForReportForMarsByMember(com.cap.bts.crmdp.dealer.redemption.dto.MemberQueryDto, java.lang.String)
    **/
    @Override
    public List<MemberPackagesReportDto> getPackageListForReportForMarsByMember(MemberQueryDto dto, Long dealerId, 
        String carMarsId) throws AppException {
        List<MemberPackagesReportDto> resultsToShow=new ArrayList<MemberPackagesReportDto>();
        
        String carPlate = null;
        if(StringUtils.isNotBlank(carMarsId)){
                MemberPackagesReportDto memberPackagesReportDto = new MemberPackagesReportDto();                
                
                List<ShowMemberPackageInfoReportDto> results=new ArrayList<ShowMemberPackageInfoReportDto>();
                List<CarPlateInfo> carPlateList = maintainCarPlateDao.getCarPlateInfoListByCarPlateForMars(dealerId, carMarsId);
                if(carPlateList != null && !carPlateList.isEmpty()){
                    CarPlateInfo carPlateInfo = carPlateList.get(0);
                    
                    carPlate = carPlateInfo.getCarPlate();
                    
                    memberPackagesReportDto.setCarPlate(carPlate);
                    
                    dto.setCarId(carPlateInfo.getId());
                    List<Object[]> list = memberPackageDao.getPackageListForReportByMember(dto);
                    if(list != null && !list.isEmpty()){
                        for (int j = 0; j < list.size(); j++) {
                            ShowMemberPackageInfoReportDto resultsDto = new ShowMemberPackageInfoReportDto();
                            Object[] obj = (Object[]) list.get(j);
                            resultsDto.setPrice((Double) obj[0]);
                            resultsDto.setName((String)obj[1]);
                            resultsDto.setPackageNumber((String)obj[2]);
                            resultsDto.setStatus((Byte)obj[3]);
                            resultsDto.setPurchaseDate(Utils.formatDate(CommonConstants.DATE_FORMAT_YYMMDD,(Date)obj[4]));
                            resultsDto.setActiveDate(Utils.formatDate(CommonConstants.DATE_FORMAT_YYMMDD,(Date)obj[5]));
                            resultsDto.setExpireDate(Utils.formatDate(CommonConstants.DATE_FORMAT_YYMMDD,(Date)obj[6]));
                            BigInteger id = (BigInteger) obj[7];
                            resultsDto.setId(id.longValue());
                            resultsDto.setCarPlate(carPlate);
                            if(resultsDto.getStatus() == 3){
                                resultsDto.setHasUnActived(true);
                            }else{
                                resultsDto.setHasUnActived(false);
                            }
                            List<Object[]> memberPackageList=packageRedemptionDao.getPackageListReportDetailByPackageId(resultsDto.getId());
                            if(memberPackageList!=null && !memberPackageList.isEmpty()){
                                resultsDto.setMemberPackageList(memberPackageList);
                                resultsDto.setHasPackage(true);
                            }else{
                                resultsDto.setHasPackage(false);
                            }
                            List<String> benfitList = packageRedemptionDao.getPackageMemberBenfitByPackageId(resultsDto.getId());
                            if(benfitList != null && !benfitList.isEmpty()){
                                String benfit = benfitList.get(0);
                                resultsDto.setBenfit(benfit);
                            }
                            //套餐使用明细
                            List<Object[]> packageRedemList = packageRedemptionDao.getPackageRedemListByPackageId(resultsDto.getId());
                            if(packageRedemList != null && !packageRedemList.isEmpty()){
                                resultsDto.setPackageRedemList(packageRedemList);
                            }
                            results.add(resultsDto); 
                        }
                        memberPackagesReportDto.setShowMemberPackageInfoReportList(results);
                    }
                }
                resultsToShow.add(memberPackagesReportDto);
        }
        return resultsToShow;
    }

    /**
     * {@inheritDoc} 
     * overridden:
     * @Date        :      2015年11月18日
     * @see com.cap.bts.crmdp.dealer.redemption.service.IRedemptionService#getMarsTenantIdByDealerId(java.lang.Long)
    **/
    @Override
    public List<DealerInfoRelMars> getMarsTenantIdByDealerId(Long dealerId) throws AppException {
        return dealerInfoSyncDao.getMarsTenantIdByDealerId(dealerId);
    }

    /**
     * {@inheritDoc} 
     * overridden:
     * @Date        :      2015年11月18日
     * @see com.cap.bts.crmdp.dealer.redemption.service.IRedemptionService#getDealerIdByMarsTenantId(java.lang.Long)
    **/
    @Override
    public List<Integer> getDealerIdByMarsTenantId(String marsTenantId) throws AppException {
        return dealerInfoSyncDao.getDealerIdByMarsTenantId(marsTenantId);
    }
    
}
